use crate::tank::Tank;
use nalgebra::Point2;

// AI感知信息结构
pub struct TankPerception {
    pub self_state: TankState,
    pub allies: Vec<TankState>,
    pub enemies: Vec<EnemyState>,
    pub obstacles: Vec<Obstacle>,
    pub powerups: Vec<Powerup>,
    pub bullets: Vec<Bullet>,
}

// 坦克状态
pub struct TankState {
    pub position: Point2<f32>,
    pub health: f32,
    pub attack_damage: f32,
    pub speed: f32,           // 添加速度属性
    pub attack_range: f32,    // 添加攻击范围属性
}

// 敌人状态
pub struct EnemyState {
    pub position: Point2<f32>,
    pub health: f32,
    pub threat_level: f32, // 威胁等级
    pub speed: f32,        // 添加速度属性
    pub attack_range: f32, // 添加攻击范围属性
}

// 障碍物
pub struct Obstacle {
    pub position: Point2<f32>,
    pub destructible: bool, // 是否可摧毁
}

// 道具
pub struct Powerup {
    pub position: Point2<f32>,
    pub powerup_type: PowerupType,
    pub remaining_time: f32,
}

pub enum PowerupType {
    Health,
    Range,
    Speed,
    Damage,
}

// 炮弹
pub struct Bullet {
    pub position: Point2<f32>,
    pub direction: Point2<f32>,
    pub owner: usize, // 所有者ID
}

// AI行为输出
pub enum TankAction {
    Move(Direction, Speed),
    Attack(TargetPoint),
    Stay,
    Retreat(SafeDirection),
}

pub struct Direction(pub f32, pub f32); // x, y方向向量
pub type Speed = f32;
pub type TargetPoint = Point2<f32>;
pub type SafeDirection = Point2<f32>;

// 坦克AI trait 添加更多方法
pub trait TankAI {
    fn decide(&mut self, perception: &TankPerception) -> TankAction;
    fn update(&mut self, dt: f32); // 添加更新方法
}

// 基础AI实现
pub struct BasicAI {
    // AI内部状态
    decision_timer: f32,
    decision_frequency: f32,
}

impl BasicAI {
    pub fn new(decision_frequency: f32) -> Self {
        BasicAI {
            decision_timer: 0.0,
            decision_frequency,
        }
    }
}

impl TankAI for BasicAI {
    fn decide(&mut self, perception: &TankPerception) -> TankAction {
        // 简单的AI决策逻辑
        // 如果有敌人在攻击范围内，则攻击
        for enemy in &perception.enemies {
            let distance = (perception.self_state.position - enemy.position).magnitude();
            if distance <= perception.self_state.attack_range {
                return TankAction::Attack(enemy.position);
            }
        }
        
        // 检查是否有道具可以拾取
        for powerup in &perception.powerups {
            let distance = (perception.self_state.position - powerup.position).magnitude();
            if distance <= 100.0 { // 如果道具在一定范围内
                return TankAction::Move(
                    Direction(
                        powerup.position.x - perception.self_state.position.x,
                        powerup.position.y - perception.self_state.position.y,
                    ), 
                    perception.self_state.speed
                );
            }
        }
        
        // 如果没有敌人在附近，随机移动
        TankAction::Move(Direction(1.0, 0.0), perception.self_state.speed)
    }
    
    fn update(&mut self, dt: f32) {
        self.decision_timer += dt;
    }
}

// 高级AI实现
pub struct AdvancedAI {
    decision_timer: f32,
    decision_frequency: f32,
    target: Option<Point2<f32>>,
    last_health: f32,
}

impl AdvancedAI {
    pub fn new(decision_frequency: f32) -> Self {
        AdvancedAI {
            decision_timer: 0.0,
            decision_frequency,
            target: None,
            last_health: 100.0,
        }
    }
    
    // 评估威胁等级
    fn evaluate_threat(&self, enemy: &EnemyState, self_position: Point2<f32>) -> f32 {
        let distance = (self_position - enemy.position).magnitude();
        // 距离越近、血量越高、攻击范围越大的敌人威胁越大
        (100.0 - distance).max(0.0) * (enemy.health / 100.0) * (enemy.attack_range / 100.0)
    }
    
    // 选择最佳目标
    fn select_target(&self, enemies: &[EnemyState], self_position: Point2<f32>) -> Option<Point2<f32>> {
        if enemies.is_empty() {
            return None;
        }
        
        let mut best_target = &enemies[0];
        let mut highest_threat = self.evaluate_threat(best_target, self_position);
        
        for enemy in enemies.iter().skip(1) {
            let threat = self.evaluate_threat(enemy, self_position);
            if threat > highest_threat {
                highest_threat = threat;
                best_target = enemy;
            }
        }
        
        Some(best_target.position)
    }
    
    // 评估是否需要撤退
    fn should_retreat(&self, self_state: &TankState) -> bool {
        self_state.health < 30.0 || self.last_health - self_state.health > 20.0
    }
}

impl TankAI for AdvancedAI {
    fn decide(&mut self, perception: &TankPerception) -> TankAction {
        self.last_health = perception.self_state.health;
        
        // 如果需要撤退
        if self.should_retreat(&perception.self_state) {
            // 寻找最近的掩体
            if let Some(obstacle) = perception.obstacles.first() {
                return TankAction::Retreat(SafeDirection::new(
                    obstacle.position.x - perception.self_state.position.x,
                    obstacle.position.y - perception.self_state.position.y,
                ));
            }
        }
        
        // 如果有明确目标，优先攻击
        if let Some(target) = self.target {
            let distance = (perception.self_state.position - target).magnitude();
            if distance <= perception.self_state.attack_range {
                return TankAction::Attack(target);
            } else {
                return TankAction::Move(
                    Direction(
                        target.x - perception.self_state.position.x,
                        target.y - perception.self_state.position.y,
                    ),
                    perception.self_state.speed,
                );
            }
        }
        
        // 选择新目标
        if let Some(target) = self.select_target(&perception.enemies, perception.self_state.position) {
            self.target = Some(target);
            return TankAction::Attack(target);
        }
        
        // 检查是否有道具可以拾取
        for powerup in &perception.powerups {
            let distance = (perception.self_state.position - powerup.position).magnitude();
            if distance <= 100.0 { // 如果道具在一定范围内
                return TankAction::Move(
                    Direction(
                        powerup.position.x - perception.self_state.position.x,
                        powerup.position.y - perception.self_state.position.y,
                    ), 
                    perception.self_state.speed
                );
            }
        }
        
        // 默认随机移动
        TankAction::Move(Direction(1.0, 0.0), perception.self_state.speed)
    }
    
    fn update(&mut self, dt: f32) {
        self.decision_timer += dt;
    }
}

